const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
// 引入url
const url =require('url');
// 获取前台用户
const frontSideRouter=require('./router/frontSide')
// 获取后台用户
const userRouter = require('./router/user');
const indexRouter=require('./router/index');
const categoryRouter=require('./router/category');
const commentRouter=require('./router/comments');
const navMenusRouter=require('./router/navMenus');
const passwordResetRouter=require('./router/password-reset');
const postAddRouter=require('./router/post-add');
const postsRouter=require('./router/posts');
const profileRouter=require('./router/profile');
const settingsRouter=require('./router/settings');
// 图片轮播
const slidesRouter=require('./router/slides');
//获取所有用户页面
const usersRouter=require('./router/users')
const app = express();
app.listen(8080, () => {
    console.log('http://127.0.0.1:8080/admin/user/login.html');
});
// 处理静态资源
app.use('/assets', express.static('assets'));
app.use('/uploads',express.static('uploads'));
// 处理post请求的数据
app.use(bodyParser.urlencoded({
    extended: false
}));

// 设置模板引擎
app.set('view engine', 'ejs');
// 注册session中间件
app.use(session({
    secret: 'sblx',
    resave: false,
    saveUninitialized: false
}))
// 实现登录权限的设置
app.use((req,res,next)=>{
    let {pathname}=url.parse(req.url);
    // console.log(pathname);
    if (pathname === '/admin/user/login.html' || pathname === '/admin/user/userLogin' || !pathname.startsWith('/admin')) {
        next(); 
    }else{
        if(req.session.isLogin){
            next();
        }else{
            res.send('<script>location.href="http://127.0.0.1:8080/admin/user/login.html"</script>')
        }
    }
})

//设置路由

// 设置前台获取页面
app.use(frontSideRouter);
// 用户
app.use('/admin/user', userRouter);
// 主页
app.use('/admin',indexRouter);
// 管理分类获取分类
app.use('/admin/category',categoryRouter);
//所有评论
app.use('/admin/comments',commentRouter);
// 导航菜单
app.use('/admin/navMenus',navMenusRouter);
// 修改密码
app.use('/admin/password-reset',passwordResetRouter);
// 写文章
app.use('/admin/post-add',postAddRouter);
// 所有文章
app.use('/admin/posts',postsRouter);
// 我的个人资料
app.use('/admin/profile',profileRouter);
// 网站设置
app.use('/admin/settings',settingsRouter);
// 图片轮播
app.use('/admin/slides',slidesRouter);
//获取所有用户页面
app.use('/admin/users',usersRouter);
